﻿using System.Collections.Generic;
using System.Configuration;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Core.DAL;
using Core.Extentions;

namespace ScoutNET.ActionsResults
{
    public class IcalContentResult : ActionResult
    {
        public List<tSite_Calendar> Events { get; private set; }
        public string SystemName { get; private set; }

        public IcalContentResult(List<tSite_Calendar> lEvents, string systemName)
        {
            this.Events = lEvents;
            this.SystemName = systemName;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.ContentType = "text/calendar";
            context.HttpContext.Response.AddHeader("Content-disposition", string.Format("attachment; filename=UniteLoverval-{0}.ics", this.SystemName));

            StringBuilder sb = new StringBuilder();

            // Header
            sb.AppendLine("BEGIN:VCALENDAR");
            sb.AppendLine("PRODID:-//Mozilla.org/NONSGML Mozilla Calendar V1.1//BE");
            sb.AppendLine("VERSION:2.0");
            sb.AppendLine("CALSCALE:GREGORIAN");
            sb.AppendLine("METHOD:PUBLISH");

            // Data
            foreach (tSite_Calendar siteEvent in this.Events)
            {
                sb.AppendLine("BEGIN:VEVENT");
                sb.AppendLine("ORGANIZER;CN=" + siteEvent.SectionName + ":MAILTO:" + siteEvent.SectionEmail);
                sb.AppendLine("DTSTART;TZID=Europe/Paris:" + siteEvent.StartDate.ToString("yyyyMMdd\\THHmmss\\Z"));
                sb.AppendLine("DTEND;TZID=Europe/Paris:" + siteEvent.EndDate.ToString("yyyyMMdd\\THHmmss\\Z"));
                sb.AppendLine("SUMMARY: ( " + siteEvent.SectionName.UppercaseFirst() + " ) " + siteEvent.Title);
                sb.AppendLine("LOCATION:" + siteEvent.Location + " ( " + siteEvent.SectionName + " )");
                sb.AppendLine("X-GOOGLE-CALENDAR-CONTENT-ICON:" + ConfigurationManager.AppSettings["SiteUrl"] + ConfigurationManager.AppSettings["LogosPath"] + "cal_" + siteEvent.SID + ".jpg");
                sb.AppendLine("DESCRIPTION;ENCODING=QUOTED-PRINTABLE:" + HttpContext.Current.Server.HtmlDecode(siteEvent.Title.ClearHTMLTags()));
                sb.AppendLine("URL:" + ConfigurationManager.AppSettings["SiteUrl"] + "/" + siteEvent.SystemName.UppercaseFirst() + "/Agenda/Index");
                sb.AppendLine("UID:" + siteEvent.ID + "@" + ConfigurationManager.AppSettings["SiteName"].Split('.')[0]);
                sb.AppendLine("X-WR-TIMEZONE;VALUE=TEXT:Europe/Paris");
                sb.AppendLine("END:VEVENT");
            }
            // Footer

            sb.AppendLine("END:VCALENDAR");

            context.HttpContext.Response.Write(sb.ToString());
            context.HttpContext.Response.End();

        }
    }
}
